package edu.johnpank.libassistant.entity

import edu.johnpank.libassistant.enums.Role
import java.io.Serializable
import java.time.LocalDateTime
import java.time.ZoneOffset
import javax.persistence.*
import javax.validation.constraints.NotEmpty
import javax.validation.constraints.Size


@Entity(name = "user_account")
class User: Serializable {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long? = null

    @NotEmpty(message = "Login is empty")
    @Size(min = 3, max = 30, message = "Must has 3 to 30 chars")
    @Column(nullable = false, unique = true)
    var login: String = ""

    @NotEmpty
    @Size(min = 5, max = 100, message = "Must has 5 to 100 chars")
    @Column(nullable = false, length = 1000)
    var password: String = ""

    @NotEmpty(message = "Email is empty")
    @Column(nullable = false, unique = true)
    var email: String = ""

    @NotEmpty
    @Size(min = 2, max = 100, message = "Must has 2 to 100 chars")
    @Column(nullable = false)
    var firstName: String = ""

    @NotEmpty
    @Size(min = 2, max = 100, message = "Must has 2 to 100 chars")
    @Column(nullable = false)
    var lastName: String = ""

    @ElementCollection(targetClass = Role::class, fetch = FetchType.EAGER)
    @CollectionTable(name = "user_role", joinColumns = [JoinColumn(name = "user_id")])
    @Enumerated(EnumType.STRING)
    @Column(name = "roles")
    var roles: MutableSet<Role> = mutableSetOf()

    @Column(nullable = false)
    var regDate: Long = 0

    @PrePersist
    private fun init(){
        if (regDate == 0L){
            regDate = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) * 1000
        }
    }

    @Column(nullable = false)
    var isConfirmed:Boolean = false

    @Column(nullable = false)
    var isAdmin:Boolean = false

    @Column(nullable = false)
    var isLibrarian:Boolean = false

    override fun toString(): String {
        return "User(id=$id, login='$login', password='$password', email='$email', firstName='$firstName', lastName='$lastName', roles=$roles, regDate=$regDate, isConfirmed=$isConfirmed)"
    }
}
